# Importing Data
SPAIN <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Israel/Spain.xlsx")

# Checking the Imported Data
View(SPAIN)

# Creating Time Series Data
SPAIN_ts <- ts(SPAIN, start=c(2004,01), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
SPAIN_ts
sum(is.na(SPAIN_ts))
library(forecast)
SPAIN_ts <- tsclean(SPAIN_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(SPAIN_ts)
plot(aggregate(SPAIN_ts,FUN=mean))

# Decomposing
SPAIN_ts_decomp <- decompose(SPAIN_ts)
plot(SPAIN_ts_decomp)

# Testing for Stationarity
acf(SPAIN_ts, lag.max=20)
pacf(SPAIN_ts, lag.max=20)

# To see any seasonal effect
boxplot(SPAIN_ts~cycle(SPAIN_ts))

# To remove trend effect
SPAIN_ts_diff <- diff(SPAIN_ts)
plot(SPAIN_ts_diff)

# To remove variance effect
SPAIN_ts_log <- log(SPAIN_ts)
plot(SPAIN_ts_log)

# To remove both (Trend and Variance) effects
SPAIN_ts_both <- diff(log(SPAIN_ts))
plot(SPAIN_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(SPAIN_ts, lag.max=20)
acf(log(SPAIN_ts), lag.max=20)
acf(diff(SPAIN_ts), lag.max=20)
acf(diff(log(SPAIN_ts)), lag.max=20)
pacf(SPAIN_ts, lag.max=20)
pacf(log(SPAIN_ts), lag.max=20)
pacf(diff(SPAIN_ts), lag.max=20)
pacf(diff(log(SPAIN_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
SPAIN_ts_model <- auto.arima(SPAIN_ts)
SPAIN_ts_model
SPAIN_ts_model <- auto.arima(SPAIN_ts, ic="aic", trace = TRUE)
SPAIN_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(SPAIN_ts_model$resid)
acf(SPAIN_ts_model$residuals, main='ACF Residual')
pacf(SPAIN_ts_model$residuals, main='ACF Residual')
Box.test(SPAIN_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
SPAIN_ts_forecast <- forecast (SPAIN_ts_model, level=c(95), h=257)
plot(SPAIN_ts_forecast)
SPAIN_ts_forecast             


write.table(SPAIN_ts_forecast, file="Spain_TSA.csv", sep=",")
